package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    /**
     * 注入mapper
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findParentDepts() {
        return departmentMapper.findParentDepts();
    }

    /**
     * ctrl+t，快速进入方法
     * @param query
     * @return
     */
    @Override
    public PageList<Department> findPage(DepartmentQuery query) {

        //1.分页插件
        PageHelper.startPage(query.getPage(), query.getSize());

        //2.封装pageInfo
        List<Department> departments = departmentMapper.findPage(query);
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        //3.返回自己封装的PageList
        return new PageList<>(pageInfo.getTotal(),pageInfo.getList());
    }



    @Override
    @Transactional
    public void saveOrUpdate(Department department) {

        //参数  细节很重要
        if (StringUtils.isBlank(department.getName())){
            throw new RuntimeException("请填写部门名称");
        }
        if (StringUtils.isBlank(department.getSn())){
            throw new RuntimeException("请填写部门编号");
        }

        //根据id区分,没有id就是新增
        if (department.getId() == null) {
            //insert:全表更新子段  insertSelective:只有设置了值的字段才会被插入
            departmentMapper.insertSelective(department);
            this.updateDirPath(department);

        } else {
            String oldDirPath = department.getDirPath();
            String dirPathStr = this.updateDirPath(department);

            if (dirPathStr != null && StringUtils.isNotBlank(department.getDirPath())){
                //1.根据修改之前的dirPath查到相关数据 like      /1/2
                List<Department> departments = departmentMapper.selectByDirPath(department.getDirPath());
                //2.处理数据
                for (Department department1 : departments) {
                    department1.setDirPath(department1.getDirPath().replace(oldDirPath,dirPathStr));
                    departmentMapper.updateByPrimaryKeySelective(department1);
                }
            }
        }
    }

    /**
     * 自动抽方法快捷  alt + shift + m
     * @param department
     */
    private String updateDirPath(Department department) {
        //1.获取上级部门路径集合
        Long[] parentIds = department.getParentIds();//[3,8,10]
        //1.处理有值的情况  效果 parentid：10 dirPath：/3/8/10/自己id
        StringBuilder sb = new StringBuilder("");
        if (parentIds != null && parentIds.length > 0){
            Long parentId = parentIds[parentIds.length-1];
            department.setParentId(parentId);

            ArrayList<Long> arrayList = new ArrayList<>();
            HashSet<Long> sets = new HashSet<>();
            //2.遍历新增 /3/8/10/自己id
            for (Long id : parentIds) {
                sb.append("/").append(id);// /3/8/10
                arrayList.add(id);
                sets.add(id);
            }
            sb.append("/").append(department.getId());
            arrayList.add(department.getId());
            sets.add(department.getId());

            if (arrayList.size() != sets.size()){
                throw new RuntimeException("不能选择自己的上级部门");
            }

        }else{
            //顶级不用处理
            sb.append("/").append(department.getId());
        }

        //设置dir_path的值
        department.setDirPath(sb.toString());

        //修改
        departmentMapper.updateByPrimaryKeySelective(department);

        return sb.toString(); // /3/2
    }

    /**
     * 获取部门树
     * @return
     */
    @Override
    public List<Department> deptTree() {
        //1.查询所有部门
        List<Department> departments = departmentMapper.selectAll();
        //2.用无限极工具类处理部门列表
        List<Department> tree = TreeUtil.getTree(departments);

        return tree;
    }
}